package com.example.tutorialspringbootstatemachine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: jie lu
 * @Data: 2021/10/19
 * @Version: 1.0
 * @Description:
 **/
public class UserStateMachineListener extends StateMachineListenerAdapter<States, Events> {
    private static final Logger logger = LoggerFactory.getLogger(UserStateMachineListener.class);

    @Override
    public void stateChanged(State<States, Events> from, State<States, Events> to) {
        logger.info("状态机从状态 {} 转换为 {}", from, to);
    }

    @Override
    public void stateEntered(State<States, Events> state) {
        logger.info("状态机进入 {} 状态", state.getId());
    }

    @Override
    public void stateExited(State<States, Events> state) {
        logger.info("状态机退出 {} 状态", state.getId());
    }

    @Override
    public void eventNotAccepted(Message<Events> event) {
        logger.info("状态机不接受 {} 事件", event.getPayload());
    }

    @Override
    public void transition(Transition<States, Events> transition) {

        logger.info("事务进行中");
    }

    @Override
    public void transitionStarted(Transition<States, Events> transition) {

        logger.info("事务开始");
    }

    @Override
    public void transitionEnded(Transition<States, Events> transition) {

        logger.info("事务结束");
    }

    @Override
    public void stateMachineStarted(StateMachine<States, Events> stateMachine) {
        logger.info("启动状态机 状态机初始状态为 {}", stateMachine.getInitialState().getId());
    }

    @Override
    public void stateMachineStopped(StateMachine<States, Events> stateMachine) {
        logger.info("启动状态机 状态机当前状态为 {}", stateMachine.getState().getId());
    }

    @Override
    public void stateMachineError(StateMachine<States, Events> stateMachine, Exception exception) {
        logger.info("状态机发生错误 当前状态为 {} 异常为 ", stateMachine.getState().getId(), exception);
    }

    @Override
    public void extendedStateChanged(Object key, Object value) {
        logger.info("状态机扩展状态改变 {} 改变为  {}", key, value);
    }

    @Override
    public void stateContext(StateContext<States, Events> stateContext) {
        StateMachine<States, Events> stateMachine = stateContext.getStateMachine();
        State<States,Events> states = stateMachine.getState();
        if(states != null) {
            States state = states.getId();
            logger.info("状态机当前状态为 {}", state);
            String userId = stateContext.getMessageHeaders().get("userId", String.class);
            if(userId != null) {
                WebSocketNotifyUtil.sendMessageToClient(userId,state.toString());
            }

        }

    }

}